package com.heima.kafka.simple;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;

import java.util.Properties;

/**
 * @author Psycho
 * @create 2022-04-29-10:44
 */
public class ProducerQuickStart {
    public static void main(String[] args) {
        KafkaProducer kafkaProducer = null;
        try {
            //1.kafka的配置信息
            Properties properties = new Properties();
            //kafka的连接地址
            properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.200.130:9092");
            //消息key的序列化器
            properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
            //消息value的序列化器
            properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");

            //2.生产者对象
            kafkaProducer = new KafkaProducer(properties);

            //封装发送的消息
            ProducerRecord producerRecord = new ProducerRecord("kafka-topic", "psycho", "hello-kafka");

            //3.发送消息
            kafkaProducer.send(producerRecord);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //4.关闭消息通道，必须关闭，否则消息发送不成功
            kafkaProducer.close();
        }
    }
}
